package com.snicesoft.jfinal.vue.handler;

import com.jfinal.handler.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

public class ProxyHandler extends Handler {

    final static List defaultSuffixs = Arrays.asList(".js", ".css", ".ico", ".png", "jpg");

    private String url;
    private String jsUrl;

    public ProxyHandler(String url, String jsUrl) {
        this.url = url;
        this.jsUrl = jsUrl;
    }

    @Override
    public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, boolean[] booleans) {
        if (s.length() > 1) {
            String filename = s;
            int pos = s.indexOf("?");
            if (pos > -1) {
                filename = s.substring(0, s.indexOf("?"));
            }
            String suffix = getSuffix(filename);
            if (suffix == null) {
                next.handle(s, httpServletRequest, httpServletResponse, booleans);
                return;
            }
            boolean isMatch = defaultSuffixs.contains(suffix);
            if (isMatch) {
                try {
                    URL url = new URL((".js".equalsIgnoreCase(suffix) ? this.jsUrl : this.url) + s);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5 * 1000);
                    conn.setRequestMethod("GET");
                    InputStream inStream = conn.getInputStream();
                    byte[] data = toByteArray(inStream);
                    httpServletResponse.setDateHeader("Expires", -1);//IE
                    httpServletResponse.setHeader("Cache-Control", "no-cache");
                    httpServletResponse.setHeader("Pragma", "no-cache");
                    httpServletResponse.getOutputStream().write(data);
                    httpServletResponse.getOutputStream().flush();
                    httpServletResponse.getOutputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return;
        }
        next.handle(s, httpServletRequest, httpServletResponse, booleans);
    }

    private String getSuffix(String fileName) {
        return fileName != null && fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".")) : null;
    }

    private byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
